<?php
namespace App\http\Models;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use App\http\Models\Knight;
use App\Helper\Functions;
use Ixudra\Curl\Facades\Curl;
use Illuminate\Support\Facades\Log;

Class AgencyOrder extends Model
{

    protected $table = 'agency_order';

     //指定主键
    protected $primaryKey = 'aoId';

    //自动维护时间戳
    public $timestamps = false;

    public $outColumn = ['aoId', 'aoCode', 'csId', 'uId', 'aaId', 'ceId', 'aoExpressWeight', 'aoLevel', 'aoPay',
                        'aoSmsCopy', 'aoMemo', 'createTime', 'aoStatus', 'aoCancelReason', 'aoCancelTime',
                        'kId', 'aoGetTime', 'aoReceive'];

    // 获取待接任务订单列表
    public function getTaskList($csId){

        // 获取加急订单
        $orderList = $this::select(['agency_order.*', 'agency_address.aaName', 'aaSex', 'aaMobile', 'ssId'
                                    , 'ssName', 'aaAddress', 'stName'])
                        ->leftJoin('agency_address', 'agency_order.aaId', '=', 'agency_address.aaId')
                        ->leftJoin('school_take', 'agency_order.stId', '=', 'school_take.stId')
                        ->where('agency_order.csId', $csId)
                        ->where('aoStatus', 0)
                        ->orderByRaw('aoLevelSort DESC, aoId ASC')
                        ->get();

        $orderList = json_decode(json_encode($orderList), true);

        return $orderList;
    }

    // 添加订单 注意参数不能超过9个
    public function add($csId, $uId, $aaId, $stId, $ceId, $ceName, $aoExpressWeight, $aoLevel, $aoServeTime, $aoPay, $aoSmsCopy, $aoMemo, $aoTakeInfo, $aoType){

//        if (empty(!$aoServeTime)){
//            $today = date("Y-m-d");
//            $aoServeTime = $today.' '.$aoServeTime.':00';
//        }

        $reflection = new \ReflectionMethod($this, __FUNCTION__);
        $parameters = $reflection->getParameters();
        $paramValues = func_get_args();

        $AgencyOrder = new AgencyOrder();
        for ($i=0;$i<count($parameters);$i++){
            if ($paramValues[$i] && $paramValues[$i] !== 0){
                $AgencyOrder[$parameters[$i]->name] = $paramValues[$i];
            }
        }

        // 添加随机订单码
        $aoCode = str_replace("-", "",  (string) Str::uuid());
        $AgencyOrder['aoCode'] = $aoCode;
        $AgencyOrder['aoStatus'] = -2;
        $aoLevelSort = 0;
        if ($aoLevel == 'normal'){
            $aoLevelSort = 10;
        } else if($aoLevel == 'urgent'){
            $aoLevelSort = 30;
        } else if($aoLevel == 'clock'){
            $aoLevelSort = 20;
        } else if($aoLevel == 'urgentClock'){
            $aoLevelSort = 40;
        }
        $AgencyOrder->aoLevelSort = $aoLevelSort;
        $AgencyOrder->save();
        return $aoCode;
    }

    // 获取用户订单列表
    public function getUserList($uId, $orderType){
        if ($orderType == 'done'){
            $list = $this::select(['agency_order.*', 'agency_address.aaName', 'aaSex', 'aaMobile', 'ssId'
                                    , 'ssName', 'aaAddress', 'stName', 'aoTakeInfo', 'aoType'])
                ->leftJoin('agency_address', 'agency_order.aaId', '=', 'agency_address.aaId')
                ->leftJoin('school_take', 'agency_order.stId', '=', 'school_take.stId')
                ->where('agency_order.uId', $uId)
                ->where(function ($query) {
                    $query->where('aoStatus', 3) // 已完成
                          ->orWhere('aoStatus', 4) // 已评论
                          ->orWhere('aoStatus', -1); // 已取消
                })
                ->orderBy('aoId', 'DESC')
                ->get();
            return $list;
        } else if ($orderType == 'undone'){
            $list = $this::select(['agency_order.*', 'agency_address.aaName', 'aaSex', 'aaMobile', 'ssId'
                                    , 'ssName', 'aaAddress', 'stName', 'aoTakeInfo', 'aoType'])
                ->leftJoin('agency_address', 'agency_order.aaId', '=', 'agency_address.aaId')
                ->leftJoin('school_take', 'agency_order.stId', '=', 'school_take.stId')
                ->where('agency_order.uId', $uId)
                ->where(function ($query) {
                    $query->where('aoStatus', 0) // 发布中
                          ->orWhere('aoStatus', 1) // 已接单
                          ->orWhere('aoStatus', 2) // 已拿取
                          ->orWhere('aoStatus', -2); // 未支付
                })
                ->orderBy('aoId', 'DESC')
                ->get();
            return $list;
        }
    }

    public function doTimeFlag($list) {
        foreach ($list as &$v) {
            $v['timeFlagDesc'] = '';
            if ($v['aoType'] == 'shop') {
                $aoTakeInfo = json_decode($v['aoTakeInfo'], true);
                if (!isset($aoTakeInfo['time_flag'])) {
                    continue;
                }
                $time_flag = [
                    '1' => '今日中午',
                    '2' => '今日中午，加急',
                    '3' => '今日下午',
                    '4' => '立即配送或今日下午，加急',
                    '5' => '明日中午',
                ];
                $v['timeFlagDesc'] = isset($time_flag[$aoTakeInfo['time_flag']]) ? $time_flag[$aoTakeInfo['time_flag']] : '';
            }
        }
        return $list;
    }

    // 获取骑士任务进行中的订单列表
    public function getKnightDoingList($kId){
        $orderList = $this::select(['agency_order.*', 'agency_address.aaName', 'aaSex', 'aaMobile', 'ssId'
                                    , 'ssName', 'aaAddress', 'stName'])
                ->leftJoin('agency_address', 'agency_order.aaId', '=', 'agency_address.aaId')
                ->leftJoin('school_take', 'agency_order.stId', '=', 'school_take.stId')
                ->where('kId', $kId)
                ->where('aoStatus', 1)
                ->orderBy('aoId')
                ->get();
        return $orderList;
    }

    // 获取骑士任务被派单列表
    public function getKnightAssignedList($kId){
        $orderList = $this::select(['agency_order.*', 'agency_address.aaName', 'aaSex', 'aaMobile', 'ssId'
                                    , 'ssName', 'aaAddress', 'stName'])
                ->leftJoin('agency_address', 'agency_order.aaId', '=', 'agency_address.aaId')
                ->leftJoin('school_take', 'agency_order.stId', '=', 'school_take.stId')
                ->where('kId', $kId)
                ->where('aoStatus', -3)
                ->orderBy('aoId')
                ->get();
        return $orderList;
    }

    // 获取骑士接单历史
    public function getOrderHistory($kId){

        $orderList = $this::select(['agency_order.*', 'agency_address.aaName', 'aaSex', 'aaMobile', 'ssId'
                                    , 'ssName', 'aaAddress', 'stName'])
                ->leftJoin('agency_address', 'agency_order.aaId', '=', 'agency_address.aaId')
                ->leftJoin('school_take', 'agency_order.stId', '=', 'school_take.stId')
                ->where('kId', $kId)
                ->where(function ($query) {
                    $query->where('aoStatus', 3)
                          ->orWhere('aoStatus', 4)
                          ->orWhere('aoStatus', -1);
                })
                ->orderBy('aoId', 'DESC')
                ->get();
        return $orderList;
    }

    // 获取骑士待转单列表
    public function getOrderToTurnList($csId){
        $orderList = $this::select(['agency_order.*', 'agency_address.aaName', 'aaSex', 'aaMobile', 'ssId'
                                    , 'ssName', 'aaAddress', 'stName'])
                ->leftJoin('agency_address', 'agency_order.aaId', '=', 'agency_address.aaId')
                ->leftJoin('school_take', 'agency_order.stId', '=', 'school_take.stId')
                ->where('aoStatus', 2)
                ->where('agency_order.csId', $csId)
                ->orderBy('aoId')
                ->get();
        return $orderList;
    }

    // 支付成功修改订单状态
    public function payChangeOrderStatus($aoCode, $uId){
        $aoInfo = $this::where('uId', $uId)
                ->where('aoCode', $aoCode)
                ->where('aoStatus', -2)
                ->first();
        if (empty($aoInfo)){
            return false;
        }
        $aoInfo->aoStatus = 0;
        $aoInfo->createTime = date('Y-m-d H:i:s', time());
        $aoInfo->save();
        return $aoInfo;
    }

    // 骑士更改订单状态
    public function knightChangeOrderStatus($kId, $aoId, $aoStatus){

        $aoInfo = $this::where('aoId', $aoId)->first();

        if (empty($aoInfo)){
            return '找不到订单';
        }

        if ($aoInfo->aoStatus == 1 || $aoInfo->aoStatus == 2){
            // 1已接单  2已拿取
            if ($aoInfo->kId != $kId){
                return '没有修改此订单权限';
            }
        } else if ($aoInfo->aoStatus == 0){
            // 发布中
            if ($aoStatus != 1 &&  $aoStatus != '1'){
                return '尚未被接单，无法修改其它状态';
            }
        } else {
            return '无修改权限';
        }

        $now = date('Y-m-d H:i:s', time());
        $Knight = new Knight();
        if ($aoStatus == 1){
            // 接单后发送打印消息
            $noticeResult = Curl::to('http://shop.sbedian.com/notify/wxpayWaimaiPrint')
                ->withData(['out_trade_no'=> $aoInfo->aoCode])
                ->get();

            $aoInfo->aoAcceptTime = $now;
            $aoInfo->kId = $kId;
            $knightInfo = Knight::find($kId);
            $aoInfo->kUid = $knightInfo->uId;
            $Knight->setKnightWorkStatus($kId, $aoStatus);
        } else if ($aoStatus == 2){
            $aoInfo->aoGetTime = $now;
        } else if ($aoStatus == 3){
            $aoInfo->aoAcceptRole = 'knight';
            $aoInfo->aoReceiveTime = $now;
            $Knight->setKnightWorkStatus($kId, $aoStatus);
        }

        $aoInfo->aoStatus = $aoStatus;
        $aoInfo->save();

        if ($aoStatus == 1){
            // 通知用户接单
            $requestPath = '/auth/acceptOrderNotice';
            $data = array();
            $data['uChannelId'] = config('services.extend.commonId');
            $data['uIds'] = $aoInfo->uId;
            $data['link'] = 'pages/index/index?page=detail&name=aoId&id='.$aoInfo->aoId;
            $data['first'] = '尊敬的校运通用户，您的订单已被接取';
            $data['orderNo'] = $aoInfo->aoCode;
            $data['money'] = $aoInfo->aoPay;
            $data['taskType'] = '代取快递';
            $data['remark'] = '点击可查看详情';
            $this->extendRequest($requestPath, $data);

            // 增加接单数
            $Knight->addGetNum($kId);
        } else if ($aoStatus == 3){
            // 通知用户完成
            $requestPath = '/auth/orderDoneNotice';
            $data = array();
            $data['uChannelId'] = config('services.extend.commonId');
            $data['uIds'] = $aoInfo->uId;
            $data['link'] = 'pages/index/index';
            $data['first'] = '尊敬的校运通用户，您的订单已完成';
            $data['orderNo'] = $aoInfo->aoCode;
            $data['money'] = $aoInfo->aoPay;
            $data['remark'] = '点击可查看详情';
            $this->extendRequest($requestPath, $data);

            // 增加完成单数
            $Knight->addDoneNum($kId);
        }

        return $aoInfo;
    }

    // 用户更改订单状态
    public function userChangeOrderStatus($uId, $aoId, $aoStatus, $aoCancelReason=''){

        $returnInfo = array();
        $returnInfo['code'] = 0;


        $aoInfo = $this::where('uId', $uId)
                ->where('aoId', $aoId)
                ->where(function ($query) {
                    $query->where('aoStatus', 0) // 发布中
                          ->orWhere('aoStatus', 1) // 已接单
                          ->orWhere('aoStatus', 2) // 已拿取
                          ->orWhere('aoStatus', -2); // 待支付
                })
                ->first();
        if (empty($aoInfo)){
            $returnInfo['code'] = 0;
            $returnInfo['msg'] = '找不到对应订单';
            return $returnInfo;
        }

        if ($aoStatus == -1){
            if ($aoInfo->aoStatus != 0 && $aoInfo->aoStatus != -2){
                $returnInfo['code'] = 0;
                $returnInfo['msg'] = '订单已被接取，无法取消';
                return $returnInfo;
            }
        } else if ($aoStatus == 3){
            if ($aoInfo->aoStatus != 1 && $aoInfo->aoStatus != 2){
                if ($aoInfo->aoStatus == 3){
                    $returnInfo['code'] = 1;
                    $returnInfo['msg'] = 'OK';
                    return $returnInfo;
                } else {
                    $returnInfo['code'] = 0;
                    $returnInfo['msg'] = '订单状态错误，无法确认已送达';
                    return $returnInfo;
                }
            }
        }else{
            $returnInfo['code'] = 0;
            $returnInfo['msg'] = '订单状态异常';
            return $returnInfo;
        }

        $aoInfo->aoStatus = $aoStatus;
        $now = date('Y-m-d H:i:s', time());
        if ($aoStatus == -1){
            $aoInfo->aoCancelTime = $now;
            $aoInfo->aoCancelReason = $aoCancelReason;
        } else if ($aoStatus == 3){
            $aoInfo->aoAcceptRole = 'user';
            $aoInfo->aoReceiveTime = $now;
        }

        $aoInfo->save();

        if ($aoStatus == 3){
            $Knight = new Knight();
            $Knight->setKnightWorkStatus($aoInfo->kId, $aoStatus);
        }

        $returnInfo['code'] = 1;
        $returnInfo['msg'] = 'OK';
        return $returnInfo;
    }

    // 获取待完成订单数量
    public function getToDoOrderNum($kId){
//        DB::connection()->enableQueryLog();#开启执行日志
        $num = $this::where('kId', $kId)
                ->where(function ($query) {
                    $query->where('aoStatus', 1) // 已接单
                          ->orWhere('aoStatus', 2); // 已拿取
//                          ->orWhere('aoStatus', -3); // 平台派单
                })
                ->count();
//        print_r(DB::getQueryLog());exit;
        return $num;
    }

    // 获取订单信息
    public function getInfo($aoId){
        $orderInfo = $this::select(['agency_order.*', 'agency_address.aaName', 'aaSex', 'aaMobile', 'ssId'
                                    , 'ssName', 'aaAddress', 'stName', 'aoTakeInfo', 'aoType'])
                ->leftJoin('agency_address', 'agency_order.aaId', '=', 'agency_address.aaId')
                ->leftJoin('school_take', 'agency_order.stId', '=', 'school_take.stId')
                ->where('aoId', $aoId)
                ->first();
        return $orderInfo;
    }

    // 获取订单信息
    public function getInfoFromAoCode($aoCode){
        $orderInfo = $this::select(['agency_order.*', 'agency_address.aaName', 'aaSex', 'aaMobile', 'ssId'
                                    , 'ssName', 'aaAddress', 'stName', 'aoTakeInfo', 'aoType'])
                ->leftJoin('agency_address', 'agency_order.aaId', '=', 'agency_address.aaId')
                ->leftJoin('school_take', 'agency_order.stId', '=', 'school_take.stId')
                ->where('aoCode', $aoCode)
                ->first();
        return $orderInfo;
    }

    /**
     * 获取学校
     */
    public function shool()
    {
        return $this->belongsTo('App\http\Models\School', 'csId', 'csId');
    }

    /**
     * 获取收货地址
     */
    public function AgencyAddress()
    {
        return $this->belongsTo('App\http\Models\AgencyAddress', 'aaId', 'aaId');
    }

    // 请求用户接口
    private function extendRequest($requestPath, $requestData=null){
        $Functions = new Functions();
        $authHost = config('services.extend.authHost');
        $requestUrl = $authHost.$requestPath;
        if (empty($requestData)){
            $data = $Functions->Get($requestUrl);
        }else{
            $data = $Functions->Post($requestUrl, $requestData);
        }
        return $data;
    }

    // 接受转单
    public function turnOrder($aoId, $kUid){

        $returnInfo = array();
        $returnInfo['code'] = 0;

        $Knight = new Knight();
        $knightInfo = $Knight->where('uId', $kUid)
                            ->where('kStatus', 1)
                            ->first();
        if (empty($knightInfo)){
            Log::error("turnOrder err:[aoId={$aoId}, kUid={$kUid}]");
            $returnInfo['msg'] = '找不到骑士信息';
            return $returnInfo;
        }

        $orderInfo = $this::where('aoId', $aoId)->first();
        if (empty($orderInfo)){
            Log::error("turnOrder err:[aoId={$aoId}, kUid={$kUid}]");
            $returnInfo['msg'] = '找不到订单信息';
            return $returnInfo;
        }
        if ($orderInfo->aoStatus != 2){
            $returnInfo['msg'] = '该单不可以转';
            return $returnInfo;
        }

        if ($orderInfo->kId == $knightInfo->kId){
            $returnInfo['msg'] = '不能转给自己';
            return $returnInfo;
        }

        $orderInfo->kId = $knightInfo->kId;
        $orderInfo->kUid = $kUid;
        $orderInfo->aoStatus = 1;
        $orderInfo->aoGetTime = date('Y-m-d h:i:s', time());
        $orderInfo->save();

        $returnInfo['code'] = 1;
        $returnInfo['msg'] = 'OK';
        return $returnInfo;
    }
}
?>
